<script>
import { areaList } from '@vant/area-data';
export default {
  setup() {
    return { areaList };
  },
  data() {
    return {
      active: 0,
      icon: {
        active: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.7GBrICZ8r5GrepghfkYLSQAAAA?rs=1&pid=ImgDetMain',
        inactive: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.7GBrICZ8r5GrepghfkYLSQAAAA?rs=1&pid=ImgDetMain'
      },
      icons: {
        active: 'https://pic.nximg.cn/file/20230213/10539202_220809301103_2.jpg',
        inactive: 'https://pic.nximg.cn/file/20230213/10539202_220809301103_2.jpg'
      },
      icong: {
        active: 'https://img.yzcdn.cn/vant/user-active.png',
        inactive: 'https://img.yzcdn.cn/vant/user-inactive.png'
      },
      iconb: {
        active: 'https://pic.nximg.cn/file/20230213/10539202_220809301103_2.jpg',
        inactive: 'https://pic.nximg.cn/file/20230213/10539202_220809301103_2.jpg'
      },

      brandList: [
        {
          icon: 'https://img.ixintu.com/download/jpg/201912/da4d9fc3ffd97234d6f9211f74fa019c.jpg!con',
          text: '法拉利',
          to: '/brandAndCar?carId=3&carName=法拉利',
        },
        {
          icon: 'https://img1.bitauto.com/appimage-630-w1/news/2022/07/01/82433d0653b64224b7214a6ae2ec9aa1.jpg',
          text: '福特',
          to: '/brandAndCar?carId=6&carName=福特',
        },
        {
          icon: 'https://ts1.cn.mm.bing.net/th/id/R-C.81d17c4c0089aed66b3ee6028503bc8d?rik=Yx%2fWIUxeAfezmA&riu=http%3a%2f%2flogo.16888.com%2flogoimage%2f20075618525119.jpg&ehk=PUJVsYh07ot6uH6UPKTbvBRQ%2bpo4jB6L5ga%2b0ivKhsA%3d&risl=&pid=ImgRaw&r=0',
          text: '宝马',
          to: '/brandAndCar?carId=7&carName=宝马',
        },
        {
          icon: 'https://img.ixintu.com/upload/jpg/20210522/b8aa521559c6b3cac83c79ba84ad4ee2_61630_800_800.jpg!ys',
          text: '五菱宏光',
          to: '/brandAndCar?carId=5&carName=五菱宏光',
        }
      ],
      // 可用的车
      cars: [],
      favorite: [],
      selectedArea: [],
      truefavorites:[],
      falsefavorites:[],
      falseAllfavorites:[],
      showToast: false,
      loadedProvinces: false,
      loadedCities: false,
      loadedCounties: false,
      flag:false,
      value: '',
      showAction: false,
      address:"",
      user:{},
    };
  },
  methods: {

    SCreen(){
      this.$router.push('/screen')
    },
    details(car){
      localStorage.setItem("cars", JSON.stringify(car))
      this.$router.push({path:'/details', query: { car : car }})
    },
    onConfirm(area) {
      // 当用户点击完成按钮时触发
      console.log('用户确认选择的地址:', area);
      this.flag = false
      area.map((item,index)=>{
        if(index == 0){
          this.address = item.name
        }else if(index == 1){
          this.address = this.address + ',' + item.name
        }if(index == 2){
          this.address = this.address + ',' + item.name
        }
      })
      console.log(this.user.userId)
      let user = {
        userId:this.user.userId,
        address:this.address
      }
      this.axios.put('http://localhost:10086/api/user/users/update',user).then(res=>{
        if(res.data.code == 200){
          this.$message.success('修改成功')
          localStorage.setItem("currentUser", JSON.stringify(user))
        }else{
          this.$message.error('修改失败')
        }
      })
      // 这里可以将选择的地址发送到后端或进行其他处理
    },
    onChange(picker, values, index) {
      // 当选项改变时触发
      console.log('Picker 实例:', picker);
      console.log('当前选中的值:', values);
      console.log('当前列对应的索引:', index);
      // 可以根据用户选择动态加载下一级数据
      if (index === 0 &&!this.loadedCities) {
        // 当用户选择了省份时，加载该省份下的城市
        this.loadCities(values[0]);
        this.loadedCities = true;
      } else if (index === 1 &&!this.loadedCounties) {
        // 当用户选择了城市时，加载该城市下的区县
        this.loadCounties(values[1]);
        this.loadedCounties = true;
      }
    },
    async loadCities(provinceCode) {
      // 模拟异步请求城市数据
      const cities = await this.fetchData(`/api/cities?province=${provinceCode}`);
      this.areaList.city_list = cities;
    },
    async loadCounties(cityCode) {
      // 模拟异步请求区县数据
      const counties = await this.fetchData(`/api/counties?city=${cityCode}`);
      this.areaList.county_list = counties;
    },
    async fetchData(url) {
      // 这里可以使用 axios 或其他工具发送请求
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const mockData = {
            // 模拟返回的数据
          };
          resolve(mockData);
        }, 1000);
      });
    },
    submitArea() {
      if (this.selectedArea.length === 3) {
        console.log('选择的地址：', this.selectedArea);
        // 这里可以添加提交地址的逻辑，例如将地址发送到后端等
      } else {
        this.showToast = true;
        setTimeout(() => {
          this.showToast = false;
        }, 2000);
      }
    },
    xialakuang(){
      this.flag = !this.flag
    },
    onSearch() {
      this.$toast(this.value);
    },
    onFocus() {
      this.showAction = true;
    },
    onCancel() {
      this.flag = false
      this.showAction = false;
    },
    messaging(){
      this.$router.push({ name: 'messaging' });
    },
    brandandCar(name){
      this.$router.push({ name: '/brandAndCar', query: { name: name} });
    },
    findFavorite(){
      this.axios.get(`http://localhost:10086/api/order/favorites/gatFavoritesAll/${this.user.userId}`).then(res=>{
      })

    },
    boxStyle(url) {
      return {
        'background-image': `url(${url})`,
        'background-size': '120px 100px', // 可以根据需要设置其他的背景属性，如背景大小、位置等
        'background-position': 'center',
        'background-repeat': 'no-repeat'
      };
    },
    shoucang(carId,isFavorite){
      console.log("收藏"+carId,isFavorite)
      if (isFavorite == 0) {
        const cars = {
          carId:carId,
          isFavorite:1,
          userId:this.user.userId
        }
        this.axios.put('http://localhost:10086/api/cars/cars/updateCar',cars).then(res=>{
          this.CarList()
        })
      }else {
        const cars = {
          carId:carId,
          isFavorite:0,
          userId:this.user.userId
        }
        this.axios.put('http://localhost:10086/api/cars/cars/updateCar',cars).then(res=>{
          this.CarList()
        })
      }



    },
    CarList(){
      this.axios.get("http://localhost:10086/api/cars/cars/getCarAll").then(res=>{
        if (res.data.code == 200) {
          this.cars = res.data.data
          console.log(this.cars)
        } else {
          this.$toast.fail('获取数据失败')
        }
      })

    },
    Favorite(){
      this.axios.get(`http://localhost:10086/api/order/favorites/selectFavoriteAll/${this.user.userId}`).then(res=>{
        if (res.data.code == 200) {
          this.favorite = res.data.data
          console.log(this.favorite)
        } else {
          this.$toast.fail('获取数据失败')
        }
      })
    },
    // ifFavorite(){
    //   this.cars.forEach((item1, index1) => {
    //     this.favorite.forEach((item2, index2) => {
    //       if (item1.carId === item2.carId) {
    //           console.log( "成功:"+item1.carId)
    //         this.truefavorites = this.truefavorites.concat(item1.carId)
    //       }else {
    //         console.log( "失败:"+item1.carId)
    //         this.falsefavorites = this.falsefavorites.concat(index1+1)
    //         let set = new Set(this.falsefavorites);
    //         let form = Array.from(set);
    //         this.falseAllfavorites = form.filter(item =>!this.truefavorites.includes(item));
    //       }
    //
    //
    //     });
    //
    //
    //
    //   });
    //   console.log(this.truefavorites)
    //   console.log(this.falseAllfavorites)
    // },
      inage(active) {
        switch (active) {
          case 1:
            this.$router.push({ name: 'rearby' });
            break;
          case 2:
            this.$router.push({ name: 'reserve' });
            break;
          case 3:
            this.$router.push({ name: 'my' });
            break;
          default:
            break;
        }
      },
    // trueFavorite(carId){
    //   if(this.truefavorites.includes(carId)){
    //     return true
    //   }else{
    //     return false
    //   }
    // },
    // falseFavorite(carId){
    //   if(this.falseAllfavorites.includes(carId)){
    //     return false
    //   }else{
    //     return true
    //   }
    // }
  },

  created() {
    this.user = JSON.parse(localStorage.getItem("currentUser"))
    if (this.user == null) {
      this.$message.error("请先登录")
      setTimeout(
          () => {
            this.$router.push({ name: 'login' });
          },
          666
      )
    }
    this.address = this.user.address
    console.log(this.user)
    this.findFavorite()
    this.CarList()

    // this.Favorite()

  }
};

</script>

<template>
  <div>
    <div class="banner">
    <header>
      <div class="user-info">
        <span>你好,{{user.nickname}}</span>
        <div class="location">
          <van-icon name="location-o" style="color: #333; font-size: 20px; margin-right: 10px; "/>
          <span>{{ address }}</span>
          <van-icon @click="xialakuang" name="arrow-down" style="color: #333; font-size: 20px; cursor: pointer;" />
        </div>
      </div>
      <van-icon @click="messaging" name="bell" class="notification-icon" />
    </header>



<!--    搜索框-->
      <div class="d3" @click="SCreen" style=" position: relative;">
        <img class="t3"   src="http://sq5qizw6e.hn-bkt.clouddn.com/s1.png">
        <span class="s1" >搜索汽车</span>
<!--        <img class="t4" src="http://sq5qizw6e.hn-bkt.clouddn.com/t1.png">-->
      </div>

<!--    轮播图-->
    <van-swipe :autoplay="3000" :height="160">
      <van-swipe-item>
        <img style="width: 100%; height: 100%;" src="
http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20250116092816.png?e=1736991419&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:ajBsBDSwzf--Q35oxH_xTdWLbng=" />
      </van-swipe-item>
      <van-swipe-item>
        <img style="width: 100%; height: 100%;"  src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20250116092801.png?e=1736991487&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:7AwHwtK7dttYUhFyhzUqGVX6JVw=" />
      </van-swipe-item>
      <van-swipe-item>
        <img style="width: 100%; height: 100%;" src="
http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20250116092816.png?e=1736991419&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:ajBsBDSwzf--Q35oxH_xTdWLbng=" />
      </van-swipe-item>
      <van-swipe-item>
        <img style="width: 100%; height: 100%;" src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/%E5%BE%AE%E4%BF%A1%E6%88%AA%E5%9B%BE_20250116092801.png?e=1736991487&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:7AwHwtK7dttYUhFyhzUqGVX6JVw=" />
      </van-swipe-item>
    </van-swipe>
    <br>


<!--    -->
    <h3>受欢迎的品牌</h3>
    <van-grid clickable :column-num="4" style="display: flex; flex-wrap: nowrap; justify-content: space-between;">
      <van-grid-item
          @click="brandandCar(item.text)"
          v-for="(item, index) in brandList"
          :key="index"
          :icon="item.icon"
          :text="item.text"
          :to="item.to"
          :url="item.url"
          style="flex: 1; background-color: #f0f0f0; border-radius: 10px; margin: 8px; text-align: center; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
      >
        <template #icon>
          <img :src="item.icon" alt="brand-icon" style="width: 60px; height: 60px; object-fit: contain; margin-bottom: 8px;" />
        </template>
        <template #text>
          <span style="font-size: 14px; color: #333; font-weight: 500;">{{ item.text }}</span>
        </template>
      </van-grid-item>
    </van-grid>
    </div>

    <div class="car-section">
      <h4>可用的车</h4>
      <div  class="car-list">
        <div @click="details(car)"  v-for="(car, index) in cars" :key="index" class="car-item">

            <div :style="boxStyle(car.imageUrl)" style="width: 120px;height: 100px">
            <img @click.stop="shoucang(car.carId,car.isFavorite)"  v-if="car.isFavorite==0"  style="position: relative; margin-top: 0px; margin-left: 100px; width: 20px;height: 20px" src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/Lovenull.png?e=1737255146&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:yu6Xduz8_A_ENt0AbJ5R2nvPYgk=">
            <img @click.stop="shoucang(car.carId,car.isFavorite)"  v-if="car.isFavorite==1" style="position: relative; margin-top: 0px; margin-left: 100px; width: 20px;height: 20px" src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/love.png?e=1737255201&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:aJpokByV4d5CkHa9XvtnnFkLDkU=">
<!--            <img  :src="car.imageUrl" :alt="car.name" class="car-image">-->
            </div>
          <div class="car-info">
            <span class="car-name">{{ car.carModel }}</span>
            <span class="car-price">￥{{ car.pricePerHour }}/小时</span>
          </div>
          <van-icon name="heart-o" class="favorite-icon" />
        </div>
      </div>
    </div>


    <div class="recommended-section">
      <h4>高档车推荐</h4>
      <div  class="car-list">
        <div @click="details(car)"  v-for="(car, index) in cars" :key="index" class="car-item">
          <div :style="boxStyle(car.imageUrl)" style="width: 120px;height: 100px">
            <img @click.stop="shoucang(car.carId,car.isFavorite)"  v-if="car.isFavorite==0"  style="position: relative; margin-top: 0px; margin-left: 100px; width: 20px;height: 20px" src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/Lovenull.png?e=1737255146&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:yu6Xduz8_A_ENt0AbJ5R2nvPYgk=">
            <img @click.stop="shoucang(car.carId,car.isFavorite)"  v-if="car.isFavorite==1" style="position: relative; margin-top: 0px; margin-left: 100px; width: 20px;height: 20px" src="http://sq4f6kqu8.hn-bkt.clouddn.com/rentalcars/love.png?e=1737255201&token=rWxRhgEIi6r6WpeIwlvhTEPMnsDCB8KqZ34tVS7A:aJpokByV4d5CkHa9XvtnnFkLDkU=">
            <!--            <img  :src="car.imageUrl" :alt="car.name" class="car-image">-->
          </div>
          <div class="car-info">
            <span class="car-name">{{ car.carModel }}</span>
            <span class="car-price">￥{{ car.pricePerHour }}/小时</span>
          </div>
          <van-icon name="heart-o" class="favorite-icon" />
        </div>
      </div>
    </div>

    <van-loading size="24px">加载中...</van-loading>
<!--    <div class="recommended-section">-->
<!--      <div class="car-list">-->
<!--        <div v-for="(car, index) in cars" :key="index" class="car-item">-->
<!--&lt;!&ndash;          <img :src="car.image" :alt="car.name" class="car-image">&ndash;&gt;-->
<!--          <div class="car-info">-->
<!--&lt;!&ndash;            <span class="car-name">{{ car.name }}</span>&ndash;&gt;-->
<!--&lt;!&ndash;            <span class="car-price">{{ car.price }}</span>&ndash;&gt;-->
<!--          </div>-->
<!--          <van-icon name="heart-o" class="favorite-icon" />-->
<!--        </div>-->
<!--      </div>-->
<!--    </div>-->









<!--    nearby-->

    <!-- 底部导航栏 -->
    <van-tabbar v-model="active">
      <van-tabbar-item @click="inage(active)">
        <span>首页</span>
        <img
            slot="icon"
            slot-scope="props"
            :src="props.active ? icon.active : icon.inactive"
        />
      </van-tabbar-item>

      <van-tabbar-item @click="inage(active)" icon="search">
        <span>附近</span>
        <img
            slot="icon"
            slot-scope="props"
            :src="props.active ? icons.active : icons.inactive"
        />

      </van-tabbar-item>


      <van-tabbar-item @click="inage(active)" icon="gem">
        <span>我的预定</span>
        <img
            slot="icon"
            slot-scope="props"
            :src="props.active ? icong.active : icong.inactive"
        />
      </van-tabbar-item>
      <van-tabbar-item @click="inage(active)" icon="user-o">我的</van-tabbar-item>
    </van-tabbar>

    <van-area
        :area-list="areaList"
        v-model="selectedArea"
        :columns-placeholder="['请选择省份', '请选择城市', '请选择区县']"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
        v-if="flag"
    />



  </div>




</template>

<style>
@import './index.css';
</style>